package inits

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"post/api/config"
	"post/internal/model"
	"sync"
)

var DB *gorm.DB
var err error

// 单例模式全局变量
var once sync.Once

func InitMysql() {
	once.Do(
		func() {
			a := config.Apps.Mysql
			dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", a.User, a.Password, a.Host, a.Port, a.Database)
			DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
			if err != nil {
				panic(err)
			}
			fmt.Println("mysql连接成功")
			DB.AutoMigrate(&model.User{}, &model.Pot{}, &model.Comment{}, &model.Like{}, &model.PotData{})
			//mysql连接池
			sqlDB, _ := DB.DB()
			sqlDB.SetMaxIdleConns(10)
			sqlDB.SetMaxOpenConns(100)
			sqlDB.SetConnMaxLifetime(0)
		})

}
